package com.mazaiting.classfile.attr.info;

import com.mazaiting.classfile.ClassReader;
import com.mazaiting.classfile.attr.entity.LocalVariableTableEntity;
import com.mazaiting.classfile.constant.ConstantPool;

import java.util.Arrays;

/**
 * 存放方法的局部变量信息
 *
 * @author mazaiting
 * @since 2021/8/12
 */
public class LocalVariableTableAttribute extends AttributeInfo{
    /**
     * 局部变量表长度 无符号 u2
     */
    private int localVariableTableLength;
    /**
     * 局部变量表数组
     */
    private LocalVariableTableEntity[] localVariableTableEntities;

    public LocalVariableTableAttribute(ConstantPool pool, int index, int length) {
        super(pool, index, length);
    }

    @Override
    public void readInfo(ClassReader reader) {
        this.localVariableTableLength = reader.readU2ToUnsignedShort();
        this.localVariableTableEntities = new LocalVariableTableEntity[localVariableTableLength];
        for (int i = 0; i < localVariableTableLength; i++) {
            this.localVariableTableEntities[i] = new LocalVariableTableEntity(
                    reader.readU2ToUnsignedShort(),
                    reader.readU2ToUnsignedShort(),
                    reader.readU2ToUnsignedShort(),
                    reader.readU2ToUnsignedShort(),
                    reader.readU2ToUnsignedShort()
            );
        }
    }

    @Override
    public String toString() {
        return "LocalVariableTableAttribute{" +
                "nameIndex=" + nameIndex +
                ", length=" + length +
                ", localVariableTableLength=" + localVariableTableLength +
                ", localVariableTableEntities=" + Arrays.toString(localVariableTableEntities) +
                '}';
    }
}
